<template>
  <main-card title="镜像管理" :tabs="getTabs()" :online-lab="true" :show-screen-space="false">
    <template #tool-btn>
      <a-button class="mr-8" @click="router.push('/mirror-manage/custom-mirror/repository-manage/list')">仓库管理</a-button>
      <a-button type="primary" @click="createMirror">创建镜像</a-button>
    </template>
    <div class="fbc mb-32">
      <a-select v-model:value="pageForm.buildStatus" class="w-140" :options="mirrorStatusList" @change="getDataList({ offset: 1 })" />
      <a-input
        v-model:value="pageForm.imageName"
        v-trim
        class="h-36"
        allow-clear
        placeholder="请输入名称"
        style="width: 268px"
        @keyup.enter="getDataList({ offset: 1 })"
      >
        <template #prefix> <i class="iconfont icon-search-line"></i> </template>
      </a-input>
    </div>
    <a-table
      :style="{ width: '100%' }"
      :columns="tableColumns"
      :data-source="dataList"
      :pagination="false"
      :loading="loading"
      @change="onTableChange"
    >
      <template #bodyCell="{ column, record }">
        <div v-if="column.dataIndex === 'buildStatus'" class="flex items-center">
          <span v-if="record.buildStatus === 3" class="error-mark"></span>
          {{ mirrorStatusList.find(item => item.value === record.buildStatus)?.label }}
          <span v-if="record.buildStatus === 1">..</span>
        </div>
        <template v-else-if="column.dataIndex == 'imageType'">
          <div>
            {{ buildTypeOption[record.buildType as 1 | 2] }}
          </div>
        </template>

        <template v-else-if="column.dataIndex == 'createTime'">
          <div>
            {{ dateFormat(record.createTime) }}
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'tools'">
          <a-dropdown placement="bottom" @click.stop>
            <a-button :data-share="record?.createType === 1" type="text" class="icon-only-btn" @click.stop>
              <i class="iconfont icon-more-line"></i>
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item
                  v-if="checkPermissions(record?.createType, record?.readOnly)"
                  class="menu-icon-item"
                  @click="editMirror(record)"
                >
                  编辑
                </a-menu-item>
                <a-menu-item class="menu-icon-item" @click="handGetBuildLog(record)"> 日志 </a-menu-item>
                <a-menu-item
                  v-if="checkPermissions(record?.createType, record?.readOnly) && record.buildStatus !== 1"
                  class="menu-icon-item"
                  @click="openDeleteModal(record)"
                >
                  删除
                </a-menu-item>
                <a-menu-item
                  v-if="checkPermissions(record?.createType, record?.readOnly)"
                  class="menu-icon-item"
                  @click="handleOpenShareModal(record)"
                >
                  分享
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
        <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
      </template>
    </a-table>
    <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
  </main-card>

  <delete-confirm-dialog
    v-model:show="showDeleteModal"
    title="确认删除"
    msg="镜像删除后，不可恢复，请确认操作"
    label="请输入镜像名称"
    :confirm-name="selectItem?.imageName"
    :loading="confirmLoading"
    @ok="onOkDeleteTask"
  />

  <share-modal
    ref="shareModalRef"
    :submit-api="mirrorManageApi.share"
    :remove-user-api="mirrorManageApi.removeShareUser"
    :get-list-api="mirrorManageApi.getShareList"
  />
  <mirror-form-model ref="mirrorFormModelRef" :after-close-fn="getDataList" />
  <build-log-modal ref="buildLogModalRef" />
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { dateFormat } from 'g6-fn'
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import ShareModal from '@/components/ShareModal/index.vue'
  import useList from '@/hooks/use-list'
  import { mirrorManageApi } from '@/services/api'
  import { filterTableColumns, replaceEmptyStr } from '@/utils'
  import { checkPermissions } from '@/utils/share'

  import { ImageType } from '../../types/index'
  import { getTabs } from '../../utils'
  import BuildLogModal from '../components/buildLogModal.vue'
  import MirrorFormModel from '../components/mirrorFormModel.vue'

  const router = useRouter()

  interface PageForm {
    imageName: string
    /**
     * 构建状态（1：创建中 2：创建成功 3.创建失败）
     */
    buildStatus: 1 | 2 | 3 | ''
    columns: 'updateTime' | 'createTime'
    order: 'desc' | 'asc'
  }
  const buildTypeOption = {
    1: 'Docker镜像导入',
    2: '根据Dockerfile构建'
  }

  // 类型
  const mirrorStatusList = [
    {
      label: '全部状态',
      value: ''
    },
    {
      label: '构建中',
      value: 1
    },
    {
      label: '构建成功',
      value: 2
    },
    {
      label: '构建失败',
      value: 3
    }
  ]

  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'imageName',
        width: 200
      },
      {
        title: '框架',
        dataIndex: 'frame',
        width: 180
      },
      {
        title: '来源',
        dataIndex: 'imageType',
        width: 200
      },
      {
        title: '仓库',
        dataIndex: 'repositoryName',
        width: 200
      },
      {
        title: '描述',
        dataIndex: 'description'
      },
      {
        title: '状态',
        dataIndex: 'buildStatus',
        width: 120
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        isSort: true,
        width: 200
      },
      {
        title: '操作',
        width: 60,
        dataIndex: 'tools'
      }
    ])
  )

  const { pageForm, dataList, getDataList, loading } = useList<PageForm, ImageType>(mirrorManageApi.customMirrorList, {
    imageName: '',
    buildStatus: '',
    columns: 'createTime',
    order: 'desc'
  })

  const onTableChange = (pagination: any, filters: any, sorter: any) => {
    if (!sorter.order) {
      getDataList({ order: 'desc', columns: 'createTime' })
      return
    }
    const order = sorter.order === 'ascend' ? 'asc' : 'desc'
    getDataList({ offset: 1, order, columns: sorter.field })
  }
  getDataList()

  /* 新增or编辑--------------------------------------------------------------------*/
  const mirrorFormModelRef = ref<InstanceType<typeof MirrorFormModel>>()
  const createMirror = () => {
    mirrorFormModelRef.value?.open()
  }
  const editMirror = (record: any) => {
    mirrorFormModelRef.value?.open(record)
  }

  /* 删除逻辑 ---------------------------------------------------------------------*/
  const selectItem = ref<ImageType>() //当前选中的应用
  const showDeleteModal = ref(false)
  const openDeleteModal = async (item: any) => {
    selectItem.value = item
    showDeleteModal.value = true
  }

  const { loading: confirmLoading, runAsync: runDelRepository } = useRequest(mirrorManageApi.delMirror)
  const onOkDeleteTask = async () => {
    await runDelRepository({}, { urlParams: { id: selectItem.value?.id } })
    message.success('操作成功')
    showDeleteModal.value = false
    getDataList()
  }

  /*----------------------------------------- 分享 --------------------------------*/
  const shareModalRef = ref<InstanceType<typeof ShareModal>>()
  const handleOpenShareModal = (item: any) => {
    shareModalRef.value?.open({
      id: item.id
    })
  }
  /*----------------------------------------- 日志 --------------------------------*/
  const buildLogModalRef = ref<InstanceType<typeof BuildLogModal>>()
  const handGetBuildLog = (item: ImageType) => {
    if (item?.id) {
      buildLogModalRef.value?.open(item?.id)
    }
  }
</script>

<style lang="less" scoped>
  .error-mark {
    margin-right: 6px;
    width: 6px;
    height: 6px;
    background-color: @danger;
    border-radius: 50%;
  }
</style>
